<template>
  <AdminLayout title="操作日志" subtitle="查看所有管理员操作记录">
    <div class="space-y-6">
      <!-- 统计卡片 -->
      <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
        <div class="bg-white rounded-lg shadow-sm p-6">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <svg class="h-8 w-8 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
              </svg>
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-500">总日志数</p>
              <p class="text-2xl font-semibold text-gray-900">{{ stats.total }}</p>
            </div>
          </div>
        </div>

        <div class="bg-white rounded-lg shadow-sm p-6">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <svg class="h-8 w-8 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-500">今日操作</p>
              <p class="text-2xl font-semibold text-gray-900">{{ stats.today }}</p>
            </div>
          </div>
        </div>

        <div class="bg-white rounded-lg shadow-sm p-6">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <svg class="h-8 w-8 text-purple-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
              </svg>
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-500">本周操作</p>
              <p class="text-2xl font-semibold text-gray-900">{{ stats.this_week }}</p>
            </div>
          </div>
        </div>

        <div class="bg-white rounded-lg shadow-sm p-6">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <svg class="h-8 w-8 text-orange-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 8v8m-4-5v5m-4-2v2m-2 4h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
              </svg>
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-500">本月操作</p>
              <p class="text-2xl font-semibold text-gray-900">{{ stats.this_month }}</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 筛选器 -->
      <div class="bg-white shadow-sm rounded-lg p-6">
        <form @submit.prevent="applyFilters" class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-6 gap-4">
          <div>
            <label for="action" class="block text-sm font-medium text-gray-700 mb-1">操作类型</label>
            <select v-model="form.action" id="action" class="block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm">
              <option value="">全部</option>
              <option value="create">创建</option>
              <option value="update">更新</option>
              <option value="delete">删除</option>
              <option value="view">查看</option>
            </select>
          </div>

          <div>
            <label for="module" class="block text-sm font-medium text-gray-700 mb-1">模块</label>
            <select v-model="form.module" id="module" class="block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm">
              <option value="">全部</option>
              <option value="products">产品管理</option>
              <option value="orders">订单管理</option>
              <option value="users">用户管理</option>
              <option value="categories">分类管理</option>
              <option value="system-settings">系统设置</option>
            </select>
          </div>

          <div>
            <label for="date_from" class="block text-sm font-medium text-gray-700 mb-1">开始日期</label>
            <input v-model="form.date_from" type="date" id="date_from" class="block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm">
          </div>

          <div>
            <label for="date_to" class="block text-sm font-medium text-gray-700 mb-1">结束日期</label>
            <input v-model="form.date_to" type="date" id="date_to" class="block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm">
          </div>

          <div>
            <label for="search" class="block text-sm font-medium text-gray-700 mb-1">搜索</label>
            <input v-model="form.search" type="text" id="search" placeholder="搜索描述" class="block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm">
          </div>

          <div class="flex items-end gap-2">
            <button type="submit" class="flex-1 inline-flex justify-center items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-gray-900 hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900">
              筛选
            </button>
            <button @click="resetFilters" type="button" class="inline-flex justify-center items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900">
              重置
            </button>
          </div>
        </form>
      </div>

      <!-- 日志列表 -->
      <div class="bg-white shadow-sm rounded-lg">
        <div class="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
          <h3 class="text-lg font-medium text-gray-900">日志记录</h3>
          <button @click="showCleanupModal = true" class="inline-flex items-center px-3 py-2 border border-transparent text-sm font-medium rounded-md text-red-700 bg-red-100 hover:bg-red-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500">
            清理旧日志
          </button>
        </div>
        
        <div class="overflow-x-auto">
          <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
              <tr>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">时间</th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作人</th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作类型</th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">模块</th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">描述</th>
                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">IP地址</th>
                <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
              </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
              <tr v-for="log in logs.data" :key="log.id" class="hover:bg-gray-50">
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                  {{ formatDate(log.created_at) }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                  {{ log.user_name }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <span :class="getActionBadgeClass(log.action)" class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full">
                    {{ getActionName(log.action) }}
                  </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                  {{ getModuleName(log.module) }}
                </td>
                <td class="px-6 py-4 text-sm text-gray-900">
                  {{ log.description }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  {{ log.ip_address }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                  <Link :href="route('admin.logs.show', log.id)" class="text-gray-600 hover:text-gray-900">
                    查看详情
                  </Link>
                </td>
              </tr>
              <tr v-if="logs.data.length === 0">
                <td colspan="7" class="px-6 py-12 text-center text-sm text-gray-500">
                  暂无日志记录
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页 -->
        <div v-if="logs.links.length > 3" class="px-6 py-4 border-t border-gray-200 flex items-center justify-between">
          <div class="flex-1 flex justify-between sm:hidden">
            <Link v-if="logs.prev_page_url" :href="logs.prev_page_url" class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
              上一页
            </Link>
            <Link v-if="logs.next_page_url" :href="logs.next_page_url" class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
              下一页
            </Link>
          </div>
          <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
            <div>
              <p class="text-sm text-gray-700">
                显示第 <span class="font-medium">{{ logs.from }}</span> 到 <span class="font-medium">{{ logs.to }}</span> 条，
                共 <span class="font-medium">{{ logs.total }}</span> 条记录
              </p>
            </div>
            <div>
              <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px">
                <Link
                  v-for="(link, index) in logs.links"
                  :key="index"
                  :href="link.url"
                  v-html="link.label"
                  :class="[
                    link.active ? 'z-10 bg-gray-900 border-gray-900 text-white' : 'bg-white border-gray-300 text-gray-500 hover:bg-gray-50',
                    index === 0 ? 'rounded-l-md' : '',
                    index === logs.links.length - 1 ? 'rounded-r-md' : '',
                    'relative inline-flex items-center px-4 py-2 border text-sm font-medium'
                  ]"
                />
              </nav>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 清理日志模态框 -->
    <div v-if="showCleanupModal" class="fixed inset-0 z-50 overflow-y-auto" aria-labelledby="modal-title" role="dialog" aria-modal="true">
      <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" @click="showCleanupModal = false"></div>
        <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
        <div class="inline-block align-bottom bg-white rounded-lg px-4 pt-5 pb-4 text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full sm:p-6">
          <form @submit.prevent="cleanupLogs">
            <div>
              <div class="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-red-100">
                <svg class="h-6 w-6 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                </svg>
              </div>
              <div class="mt-3 text-center sm:mt-5">
                <h3 class="text-lg leading-6 font-medium text-gray-900" id="modal-title">
                  清理旧日志
                </h3>
                <div class="mt-4">
                  <label for="cleanup_days" class="block text-sm font-medium text-gray-700 text-left mb-2">
                    删除多少天前的日志
                  </label>
                  <input
                    v-model.number="cleanupForm.days"
                    type="number"
                    id="cleanup_days"
                    min="1"
                    max="365"
                    required
                    class="block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                    placeholder="例如: 30"
                  />
                  <p class="mt-2 text-sm text-gray-500 text-left">
                    将删除 {{ cleanupForm.days }} 天前的所有日志记录
                  </p>
                </div>
              </div>
            </div>
            <div class="mt-5 sm:mt-6 sm:grid sm:grid-cols-2 sm:gap-3 sm:grid-flow-row-dense">
              <button type="submit" :disabled="processing" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-600 text-base font-medium text-white hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 sm:col-start-2 sm:text-sm disabled:opacity-50">
                {{ processing ? '处理中...' : '确认删除' }}
              </button>
              <button @click="showCleanupModal = false" type="button" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 sm:mt-0 sm:col-start-1 sm:text-sm">
                取消
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </AdminLayout>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { router, Link } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import { useNotification } from '@/composables/useNotification'

const props = defineProps({
  logs: Object,
  stats: Object,
  actionStats: Object,
  moduleStats: Object,
  filters: Object,
})

const { showSuccess, showError } = useNotification()

const form = reactive({
  action: props.filters.action || '',
  module: props.filters.module || '',
  user_id: props.filters.user_id || '',
  date_from: props.filters.date_from || '',
  date_to: props.filters.date_to || '',
  search: props.filters.search || '',
})

const showCleanupModal = ref(false)
const processing = ref(false)
const cleanupForm = reactive({
  days: 30,
})

const applyFilters = () => {
  router.get(route('admin.logs.index'), form, {
    preserveState: true,
    preserveScroll: true,
  })
}

const resetFilters = () => {
  form.action = ''
  form.module = ''
  form.user_id = ''
  form.date_from = ''
  form.date_to = ''
  form.search = ''
  applyFilters()
}

const cleanupLogs = () => {
  processing.value = true
  router.post(route('admin.logs.cleanup'), cleanupForm, {
    onSuccess: () => {
      showSuccess('清理成功', '旧日志已删除')
      showCleanupModal.value = false
      processing.value = false
    },
    onError: () => {
      showError('清理失败', '请稍后重试')
      processing.value = false
    },
  })
}

const formatDate = (date) => {
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  })
}

const getActionName = (action) => {
  const names = {
    create: '创建',
    update: '更新',
    delete: '删除',
    view: '查看',
    login: '登录',
    logout: '登出',
  }
  return names[action] || action
}

const getModuleName = (module) => {
  const names = {
    products: '产品管理',
    orders: '订单管理',
    users: '用户管理',
    categories: '分类管理',
    'system-settings': '系统设置',
    'specification-templates': '规格模板',
  }
  return names[module] || module
}

const getActionBadgeClass = (action) => {
  const classes = {
    create: 'bg-green-100 text-green-800',
    update: 'bg-blue-100 text-blue-800',
    delete: 'bg-red-100 text-red-800',
    view: 'bg-gray-100 text-gray-800',
  }
  return classes[action] || 'bg-gray-100 text-gray-800'
}
</script>

